import React, { useState, useEffect, useContext } from 'react';
import { message, Card, Button } from 'antd';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';

const withAuth = (WrappedComponent) => {
    return (props) => {
        const { t } = useTranslation();
        const navigate = useNavigate();
       const [userName, setUserName] = useState('');
        useEffect(() => {
            const storedToken = localStorage.getItem('enc_token');
            const storedUserName = localStorage.getItem('username');
            if (storedUserName) {
                setUserName(storedUserName);
            }
            if (!storedToken) {
                message.warning(t('请先登录'));
                navigate('/login');
            }
        }, []);

        if (!localStorage.getItem('enc_token')) {
            return (
                <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
                    <Card>
                        <p>{t('您需要登录才能访问此页面')}</p>
                        <Button type="primary" onClick={() => navigate('/login')}>
                            {t('前往登录')}
                        </Button>
                    </Card>
                </div>
            );
        }
        return <WrappedComponent {...props} />;
    };
};

export default withAuth;